import { defineComponent, ref, watch, onMounted } from 'vue'
import { TreeSelect } from 'ant-design-vue'
import PropTypes from '@/utils/PropTypes'
export default defineComponent({
  name: 'SelectTree',
  props: {
    treeData: PropTypes.array<any>().def([]),
    id: PropTypes.any(),
    expandAll: PropTypes.bool().def(false),
    fieldName: PropTypes.object().def({}),
    multiple: PropTypes.bool().def(false),
  },
  emits: ['update:id'],
  setup(props, { emit }) {
    const searchValue = ref<string | string[]>(props.id!)
    const treeDatas = ref<any[]>([])
    onMounted(() => {
      searchValue.value != '0' && emit('update:id', searchValue)
    })
    watch(
      () => props.treeData,
      () => {
        treeDatas.value = props.treeData
      },
    )
    watch(
      () => props.id,
      () => {
        searchValue.value = props.id!
      },
    )
    watch(
      () => searchValue.value,
      (val) => {
        emit('update:id', val)
      },
    )
    return () => (
      <div>
        <TreeSelect
          v-model:value={searchValue.value}
          show-search
          allowClear
          multiple={props.multiple}
          style="width: 100%"
          dropdown-style={{ maxHeight: '400px', overflow: 'auto' }}
          tree-data={treeDatas.value}
          tree-default-expand-all={props.expandAll}
          placeholder="请选择上级菜单"
          field-names={props.fieldName}
          tree-node-filter-prop="name"
        />
      </div>
    )
  },
})
